// import { Base_Api } from '/config/index.js';

const app = getApp()
const { Base_Api } = app.require("/config/index.js")

import { getCategoryList, getCategoryListItems } from '../../../services/good/fetchCategoryList';
Page({
  data: {
    list: [],
    items_arr: [],
    activeKey: 0,
  },
  async init() {
    try {
      getCategoryList().then((res) => {
        console.log("获取分类结果成功", res)
        let category = res.data.value
        // {id , name}
        this.setData({
          list: category,
        });

        this.get_category_items_fn()
      }).catch((err) => {
        console.log(err)
      })

    } catch (error) {
      console.error('err:', error);
    }
  },

  get_category_items_fn() {
    let sel_cat = this.data.list[this.data.activeKey]
    getCategoryListItems({
      category_id: sel_cat.id
    }).then((res) => {
      res.data.value.map((item) => {
        item.image = Base_Api + item.image
      })
      this.setData({
        items_arr: res.data.value
      })

    }).catch((err) => {
      console.log(err)
    })
  },

  leftChangeFn(ev) {
    this.setData(
      {
        activeKey: ev.detail.activeKey,
      },
      () => {
        this.get_category_items_fn()
      },
    );
  },

  itemClickFn(ev) {
    console.log("元素点击事件")
    console.log(ev)

    // let categoryIndex = ev.detail.categoryIndex
    let categoryItemIndex = ev.detail.categoryItemIndex
    let categoryItem = this.data.items_arr[categoryItemIndex]

    wx.navigateTo({
      url: `/pages/goods/list/index?categoryItem_id=${categoryItem.id}`,
    });
  },

  onShow() {
    this.getTabBar().init();
  },
  onChange() {
    wx.navigateTo({
      url: '/pages/goods/list/index',
    });
  },
  onLoad() {
    this.init(true);
  },
});
